package com.mvkcloud.open.aspect;

import com.mvkcloud.open.context.TenantContext;
import com.mvkcloud.open.meta.TenantApi;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class TenantAspect {

    @Autowired
    private Environment env;


    @Around("execution(* com.mvkcloud.open.controller.*.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        TenantApi tenantApi = point.getTarget().getClass().getAnnotation(TenantApi.class);
        if (null != tenantApi) {

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            Signature signature = point.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            String appId = request.getHeader("appId");
            String appKey = request.getHeader("appKey");
            Object[] args = point.getArgs();


            TenantContext.init(appId, appKey);
            return point.proceed();
        }

        throw new RuntimeException( "error.open.tenant.secret");
    }
}
